<template>
  <div class="container">
    <div class="title">
      <el-button @click="toNew()" type="success" size="small" class="newAdd">新增</el-button>
    </div>
    <el-table v-loading="isLoading" :data="tableData" border style="width: 100%">
      <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
      <el-table-column prop="name" label="名字" width="180"></el-table-column>
      <el-table-column label="主图">
        <template slot-scope="scope">
          <img style="width: 160px;display:block;margin: 0 auto;" :src="scope.row.coverImg" />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="pageHandle"
      background
      layout="prev, pager, next"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { getBag, delOne } from '../../api/products'

export default {
  data() {
    return {
      tableData: [],
      total: 0, // 总数量
      isLoading: false
    }
  },
  created() {
    this.loadData(1) // 初始化的时候加载数据
  },
  methods: {
    // 新增
    toNew() {
      this.$router.push({
        name: 'bagAdd'
      })
    },
    // 编辑
    handleEdit(item) {
      this.$router.push({
        name: 'ProductEdit',
        query: {
          id: item._id // eslint-disable-line
        }
      })
    },
    handleDelete(item) {
      this.$confirm('是否删除此项内容', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // eslint-disable-next-line space-before-function-paren
        .then(async () => {
          await delOne(item._id) // eslint-disable-line
          this.loadData(1)
        })
        .catch(() => {
          Message.info('用户取消删除')
        })
    },
    // 加载数据
    async loadData(page) {
      this.isLoading = true
      const res = await getBag(page)
      this.tableData = res.products
      this.total = res.totalCount
      this.isLoading = false
    },
    // 分页控件改变页码
    pageHandle(p) {
      this.loadData(p)
    }
  }
}
</script>

<style>
.title {
  margin: 20px 0 0 20px;
}
</style>

